<template>
  <div class="goods-container animate__animated animate__fadeIn">
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入商品名称"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择分类"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="item in categories"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search">
            搜索
          </el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <span>商品列表</span>
          <div>
            <el-button type="primary" @click="handleAdd" icon="Plus">
              添加商品
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="filteredGoods"
        v-loading="loading"
        style="width: 100%"
        stripe
        border
        row-key="id"
        max-height="600"
        :scrollbar-always-on="true"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="商品名称" width="300" />
        <el-table-column label="商品图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imgSrc"
              :preview-src-list="[row.imgSrc]"
              fit="cover"
              class="goods-image"
              :initial-index="0"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column label="价格" width="150">
          <template #default="{ row }">
            <div class="price-container">
              <span class="original-price">¥{{ row.price }}</span>
              <span class="discount-price">¥{{ row.DiscountPrice }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="350">
          <template #default="{ row }">
            <el-tag v-if="row.size" type="info" class="spec-tag">
              {{ row.size }}
            </el-tag>
            <el-tag v-if="row.color" type="info" class="spec-tag">
              {{ row.color }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="150">
          <template #default="{ row }">
            <el-switch
              v-model="row.state"
              :active-value="1"
              :inactive-value="0"
              active-text="上架"
              inactive-text="下架"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(row)"
              icon="Edit"
            ></el-button>
            
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加商品' : '编辑商品'"
      width="800px"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="goodsForm"
        :rules="goodsRules"
        label-width="100px"
        label-position="top"
        status-icon
      >
        <el-row :gutter="20">
              <el-input v-model="goodsForm.name" placeholder="请输入商品名称" />
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="goodsForm.name" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="商品分类" prop="category">
              <el-select
                v-model="goodsForm.category"
                placeholder="请选择商品分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in categories"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input-number
                v-model="goodsForm.price"
                :min="0"
                :precision="2"
                :step="10"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="折扣价格" prop="DiscountPrice">
              <el-input-number
                v-model="goodsForm.DiscountPrice"
                :min="0"
                :precision="2"
                :step="10"
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>

          <el-col :span="12">
            <el-form-item label="商品图片" prop="imgSrc">
              <div class="image-upload-container">
                <el-tabs v-model="imageInputType" class="image-tabs">
                  <el-tab-pane label="上传图片" name="upload">
                    <el-upload
                      class="avatar-uploader"
                      action="#"
                      :show-file-list="false"
                      :auto-upload="false"
                      :on-change="handleImageChange"
                    >
                      <img
                        v-if="goodsForm.imgSrc && imageInputType === 'upload'"
                        :src="goodsForm.imgSrc"
                        class="avatar"
                      />
                      <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>
                  </el-tab-pane>
                  <el-tab-pane label="图片链接" name="url">
                    <el-input
                      v-model="goodsForm.imgSrc"
                      placeholder="请输入图片URL链接"
                      clearable
                      @change="handleImageUrlChange"
                    >
                      <template #append>
                        <el-button @click="previewImageUrl">预览</el-button>
                      </template>
                    </el-input>
                    <div v-if="goodsForm.imgSrc && imageInputType === 'url'" class="url-image-preview">
                      <img :src="goodsForm.imgSrc" class="preview-image" />
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品尺码" prop="size">
              <el-select
                v-model="goodsForm.size"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择尺码"
                style="width: 100%"
              >
                <el-option
                  v-for="item in sizeOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品颜色" prop="color">
              <el-input
                v-model="colorInput"
                placeholder="输入颜色后按回车添加"
                @keyup.enter="addColor"
                clearable
              />
              <div class="color-tags">
                <el-tag
                  v-for="color in goodsForm.color"
                  :key="color"
                  closable
                  @close="removeColor(color)"
                  class="color-tag"
                >
                  {{ color }}
                </el-tag>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="goodsForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            :loading="formLoading"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllGoods, addGoods, updateGoods, deleteGoods } from '../../api/goods'
import 'animate.css'


const goodsList = ref([])
const filteredGoods = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const dialogVisible = ref(false)
const dialogType = ref('add')
const formLoading = ref(false)
const formRef = ref(null)
const imageInputType = ref('upload')
const colorInput = ref('')
const goodsForm = ref({
  id: '',
  name: '',
  description: '',
  category: '',
  imgSrc: '',
  price: 0,
  DiscountPrice: 0,
  size: [],
  color: [],
  storeId: 1
})

// 处理对话框关闭
const handleDialogClose = (done) => {
  if (formLoading.value) {
    ElMessage.warning('正在提交表单，请稍候...')
    return
  }
  
  // 如果表单已修改，显示确认对话框
  if (goodsForm.value.name || goodsForm.value.imgSrc) {
    ElMessageBox.confirm('确定要关闭吗？未保存的数据将会丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      resetForm()
      done()
    }).catch(() => {
      // 取消关闭
    })
  } else {
    resetForm()
    done()
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  goodsForm.value = {
    id: '',
    name: '',
    description: '',
    category: '',
    imgSrc: '',
    price: 0,
    DiscountPrice: 0,
    size: [],
    color: [],
    storeId: 1
  }
}

const searchForm = ref({
  name: '',
  category: ''
})

const categories = ref([
  '卫衣', 'T恤', '外套', '套装', '裙装', '裤装', '上衣', '针织毛衣', '连衣裙', '牛仔裤'
])

const sizeOptions = ref(['XS', 'S', 'M', 'L', 'XL', 'XXL', '均码'])
const goodsRules = ref({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 100, message: '商品名称长度应在2-100个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('价格必须大于0'));
        } else if (value > 99999) {
          callback(new Error('价格不能超过99999'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  DiscountPrice: [
    { required: true, message: '请输入折扣价格', trigger: 'blur' },
    { type: 'number', message: '折扣价格必须为数字', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error('折扣价格不能小于0'));
        } else if (value > goodsForm.value.price) {
          callback(new Error('折扣价格不能高于原价'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  imgSrc: [
    { required: true, message: '请上传商品图片', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请上传商品图片'));
        } else if (!value.startsWith('data:image/') && !value.startsWith('http')) {
          callback(new Error('图片格式不正确'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  description: [
    { max: 500, message: '商品描述不能超过500个字符', trigger: 'blur' }
  ],
  size: [
    {
      validator: (rule, value, callback) => {
        if (value && value.length > 10) {
          callback(new Error('最多可选10个尺码'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  color: [
    {
      validator: (rule, value, callback) => {
        if (value && value.length > 10) {
          callback(new Error('最多可选10个颜色'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
})

// 获取商品列表
const fetchGoods = async () => {
  try {
    loading.value = true
    const res = await getAllGoods()
    
    // 处理数据，合并相同商品的不同规格
    const mergedData = mergeGoods(res.data)
    goodsList.value = mergedData
    filteredGoods.value = mergedData
    total.value = mergedData.length
    
    // 初始化分页数据
    updatePagination()
  } catch (error) {
    ElMessage.error(error.message || '获取商品列表失败')
  } finally {
    loading.value = false
  }
}
const mergeGoods = (goodsData) => {
  const goodsMap = new Map()
  
  goodsData.forEach(item => {
    const key = `${item.name}-${item.category}`
    
    if (goodsMap.has(key)) {
      // 合并规格
      const existing = goodsMap.get(key)
      if (item.size && !existing.size.includes(item.size)) {
        existing.size = existing.size ? `${existing.size},${item.size}` : item.size
      }
      if (item.color && !existing.color.includes(item.color)) {
        existing.color = existing.color ? `${existing.color},${item.color}` : item.color
      }
    } else {
      // 新商品
      goodsMap.set(key, {...item})
    }
  })
  
  return Array.from(goodsMap.values())
}
const updatePagination = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  filteredGoods.value = goodsList.value.slice(start, end)
}
// 搜索商品
const handleSearch = () => {
  const results = goodsList.value.filter(item => {
    const nameMatch = searchForm.value.name 
      ? item.name.includes(searchForm.value.name)
      : true
    const categoryMatch = searchForm.value.category
      ? item.category === searchForm.value.category
      : true
    return nameMatch && categoryMatch
  })
  
  total.value = results.length
  currentPage.value = 1
  filteredGoods.value = results.slice(0, pageSize.value)
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    category: ''
  }
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  updatePagination()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  updatePagination()
}

// 图片上传处理
const handleImageChange = (file) => {
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }

  // 验证文件大小（限制为2MB）
  const isLt2M = file.raw.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }

  // 使用FileReader预览图片
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    // 更新表单中的图片URL
    goodsForm.value.imgSrc = reader.result
  }
  reader.onerror = (error) => {
    console.error('图片读取失败:', error)
    ElMessage.error('图片读取失败，请重试')
  }
}

// 处理图片URL输入
const handleImageUrlChange = (url) => {
  // URL变化时可以在这里添加验证逻辑
  if (!url) return
  
  // 简单验证URL格式
  if (!url.match(/^(http|https):\/\/[^ "]+$/)) {
    ElMessage.warning('请输入有效的图片URL')
  }
}

// 预览图片URL
const previewImageUrl = () => {
  if (!goodsForm.value.imgSrc) {
    ElMessage.warning('请先输入图片URL')
    return
  }
  
  // 创建一个临时图片对象来验证URL是否有效
  const img = new Image()
  img.onload = () => {
    ElMessage.success('图片加载成功')
  }
  img.onerror = () => {
    ElMessage.error('图片URL无效或无法访问')
  }
  img.src = goodsForm.value.imgSrc
}

// 添加颜色
const addColor = () => {
  const color = colorInput.value.trim()
  if (!color) return
  
  // 检查是否已存在
  if (!goodsForm.value.color.includes(color)) {
    goodsForm.value.color.push(color)
  }
  
  // 清空输入
  colorInput.value = ''
}

// 移除颜色
const removeColor = (color) => {
  const index = goodsForm.value.color.indexOf(color)
  if (index !== -1) {
    goodsForm.value.color.splice(index, 1)
  }
}
const previewImageList = computed(() => {
  return filteredGoods.value.map(item => item.imgSrc)
})

// 添加商品
const handleAdd = () => {
  dialogType.value = 'add'
  goodsForm.value = {
    id: '',
    name: '',
    description: '',
    category: '',
    imgSrc: '',
    price: 0,
    DiscountPrice: 0,
    size: [],
    color: [],
    storeId: 1
  }
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  dialogType.value = 'edit'
  goodsForm.value = {
    id: row.id,
    name: row.name,
    description: row.description,
    category: row.category,
    imgSrc: row.imgSrc,
    price: parseFloat(row.price),
    DiscountPrice: parseFloat(row.DiscountPrice),
    size: row.size ? row.size.split(',') : [],
    color: row.color ? row.color.split(',') : [],
    storeId: row.storeId
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();
    formLoading.value = true;

    // 验证必要字段
    if (!goodsForm.value.imgSrc) {
      throw new Error('请上传商品图片');
    }

    // 处理商品数据
    const data = {
      name: goodsForm.value.name,
      description: goodsForm.value.description || '',
      category: goodsForm.value.category,
      imgSrc: goodsForm.value.imgSrc,
      price: parseFloat(goodsForm.value.price).toFixed(2),
      DiscountPrice: parseFloat(goodsForm.value.DiscountPrice).toFixed(2),
      size: Array.isArray(goodsForm.value.size) ? goodsForm.value.size.join(',') : '',
      color: Array.isArray(goodsForm.value.color) ? goodsForm.value.color.join(',') : '',
      storeId: goodsForm.value.storeId || 1
    };

    // 验证价格关系
    if (parseFloat(data.DiscountPrice) > parseFloat(data.price)) {
      throw new Error('折扣价不能高于原价');
    }

    if (dialogType.value === 'add') {
      await addGoods(data);
      ElMessage({
        type: 'success',
        message: '添加商品成功',
        duration: 2000
      });
    } else {
      // 编辑模式需要传入ID
      data.id = goodsForm.value.id;
      await updateGoods(data);
      ElMessage({
        type: 'success',
        message: '更新商品成功',
        duration: 2000
      });
    }

    // 关闭对话框并刷新列表
    dialogVisible.value = false;
    await fetchGoods();

    // 重置表单
    goodsForm.value = {
      id: '',
      name: '',
      description: '',
      category: '',
      imgSrc: '',
      price: 0,
      DiscountPrice: 0,
      size: [],
      color: [],
      storeId: 1
    };
  } catch (error) {
    if (error.name === 'ValidationError') {
      ElMessage({
        type: 'warning',
        message: '请检查表单填写是否正确',
        duration: 3000
      });
    } else {
      console.error('商品操作失败:', error);
      ElMessage({
        type: 'error',
        message: error.message || '操作失败，请重试',
        duration: 3000
      });
    }
  } finally {
    formLoading.value = false;
  }
};

// 修改商品状态
const handleStatusChange = async (row) => {
  try {
    await updateGoods({
      id: row.id,
      state: row.state
    })
    ElMessage.success(row.state === 1 ? '商品已上架' : '商品已下架')
    fetchGoods()
  } catch (error) {
    row.state = row.state === 1 ? 0 : 1 // 恢复原状态
    ElMessage.error(error.message || '操作失败')
  }
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除商品 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteGoods(row.id)
      ElMessage.success('删除商品成功')
      fetchGoods()
    } catch (error) {
      ElMessage.error(error.message || '删除商品失败')
    }
  })
}

onMounted(() => {
  fetchGoods()
})
</script>

<style scoped>
.goods-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.goods-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: zoom-in;
  transition: transform 0.3s;
}

.goods-image:hover {
  transform: scale(1.1);
}

.price-container {
  display: flex;
  flex-direction: column;
}

.original-price {
  text-decoration: line-through;
  color: #999;
  font-size: 12px;
}

.discount-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 14px;
}

.spec-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

/* 上传图片样式 */
.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 表格行动画 */
.el-table__row {
  transition: all 0.3s;
}

.el-table__row:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 图片URL输入和预览样式 */
.image-upload-container {
  width: 100%;
}

.image-tabs {
  margin-bottom: 10px;
}

.url-image-preview {
  margin-top: 10px;
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 颜色标签样式 */
.color-tags {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.color-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>

<style>
.el-form-item__content{
      min-width: 180px;
}
</style>